import React from "react";
import { FlatList, StyleSheet, Text, } from "react-native";
import { View,TouchableOpacity } from "react-native-ui-lib";
import { commonStyles } from "../../configs/commonStyle";
import BasePage from "../BasePage";
import ListSeparator from "../common/ListSeparator";
import ListEmpty from "../common/ListEmpty";
import NavigationBar from "../common/NavigationBar";
import ViewUtils from "../../utils/ViewUtils";
import { inject, observer } from "mobx-react";
import { Icon } from "../components";
import ConfirmDialog from "../common/ConfirmDialog";
import { uploadRecord } from "../../net/common";
import api from "../../net/api";
import ToastUtils from "../../utils/ToastUtils";
import Events from "../../utils/events";
/**
 * 上传失败录音
 */
@inject("userStore")
@observer
export default class UploadFailRecord extends BasePage {

  constructor(props) {
    super(props);
    this.selectNo;
    this.operateType;
    this.state = {
      uploadingIds: []
    }
  }

  componentDidMount() {
    super.componentDidMount();
  }

  setUploading = (recordingNo, type) => {
    const { uploadingIds } = this.state
    const targetList = type == 'add' ? uploadingIds.concat([recordingNo]) : uploadingIds.filter(item => item != recordingNo)
    this.setState({'uploadingIds': targetList})
  }

  deleteItem=()=>{
    const { uploadFailList, setValue } = this.props.userStore;
    const tempList = uploadFailList.filter(data => data.recordingNo != this.selectNo);
    logger('剩余数据', tempList)
    setValue('uploadFailList',tempList)
  }

  uploadItem=()=> {
    try {
      const { uploadFailList, setValue } = this.props.userStore;
      const record = uploadFailList.find(data => data.recordingNo == this.selectNo);
      this.setUploading(this.selectNo, 'add')
      let paramsVideo = new FormData();
      paramsVideo.append("file", {
        uri: record.videoUri,
        type: "audio/aar",
        name: record.videoUri && record.videoUri.substring(record.videoUri.lastIndexOf("\/") + 1),
      });
      paramsVideo.append("order_no", record.recordingNo);
      paramsVideo.append("track_length", record.track_length || 0);
      paramsVideo.append("isDance", record.isDance);
      paramsVideo.append("orderService", record.orderService);
      uploadRecord(paramsVideo).then(res => {
        if (res && !IsNullOrEmpty(res.key)) {
          logger("上传录音成功", res);
          ToastUtils.showInfo('上传录音成功：' + record.recordingNo)
          const tempList = uploadFailList.filter(data => data.recordingNo != record.recordingNo);
          setValue("uploadFailList", tempList);
          Events.publish("RefreshOrderList");
        }
      }).catch(e => {
        logger("上传失败", e);
        try {
          uploadError(`调用上传失败3：${api.uploadRecord}`, `调用上传失败3：${api.uploadRecord}，单号：${record.recordingNo},\n${JSON.stringify(e)}`);
        } catch (e) {
        }
      }).finally(() => {
        this.setUploading(this.selectNo, 'remove')
      })
    } catch (error) {
      this.setUploading(this.selectNo, 'remove')
      ToastUtils.showFailInfo('上传失败：' + error.message)
    }
  }

  render_item = ({ item, index }) => {
    const { uploadingIds } = this.state
    return (
      <View style={{...styles.item,marginTop:index==0?10:0}}>
        <View center flex>
          <Text style={commonStyles.text_black_13}>{item?.day}</Text>
        </View>
        <View center flex>
          <Text style={commonStyles.text_black_13}>{item?.recordingNo}</Text>
        </View>
          {
            uploadingIds.includes(item.recordingNo) ? <Text>上传中...</Text> :
            <TouchableOpacity padding-10 activeOpacity={1} onPress={()=>{
              this.operateType = 'upload';
              this.selectNo=item.recordingNo
              this.confirmDialog.show('确定要上传吗？')
            }}>
              <Icon type="AntDesign" name={'upload'} size={19} color={'#BCBCBC'} />
            </TouchableOpacity>
          }
          <TouchableOpacity padding-10 activeOpacity={1} onPress={()=>{
            this.operateType = 'delete';
            this.selectNo=item.recordingNo
            this.confirmDialog.show('确定要删除吗？')
          }}>
            <Icon type="AntDesign" name={'delete'} size={19} color={'#BCBCBC'} />
          </TouchableOpacity>
      </View>
    );
  };

  renderHeader = () => {
    return (
      <View padding-10 bg-white>
        <Text style={commonStyles.text_gray}>所有录音上传失败会在此列表显示，App会在回到首页时，自动上传所有失败的录音。</Text>
      </View>
    );
  };

  render() {
    const { uploadFailList,userInfo } = this.props.userStore;
    const dataList = uploadFailList.filter(data => data.distributorId == userInfo.distributorId);

    return (
      <View useSafeArea style={commonStyles.body_primary}>
        <NavigationBar
          title={"录音待上传"}
          backgroundColor={"transparent"}
          leftButton={ViewUtils.getLeftButton(() => this._onBackPress())}
        />
        <View style={commonStyles.container}>
          <FlatList
            data={dataList}
            showsVerticalScrollIndicator={false}
            extraData={this.state}
            style={{}}
            contentContainerStyle={{ flexGrow: 1 }}
            keyExtractor={(item, index) => "menu_" + index}
            renderItem={this.render_item}
            ItemSeparatorComponent={() => <ListSeparator height={0.5} backgroundColor={"#F7F7F7"} />}
            ListEmptyComponent={() => <ListEmpty showEmpty={IsNullOrEmpty(dataList)} />}
          />
        </View>
        <ConfirmDialog
          ref={r => (this.confirmDialog = r)}
          callBack={() => {
            this.operateType === 'delete' ? this.deleteItem() : this.uploadItem()
          }}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  titleWrap: {
    justifyContent: "space-between",
    flexDirection: "row",
    alignItems: "center",
    borderTopLeftRadius: 4,
    borderTopRightRadius: 4,
    backgroundColor: "#F9D63B",
    paddingHorizontal: 15,
    paddingVertical: 10,
    marginTop: 15,
  },
  item: {
    flexDirection: "row",
    alignItems: "center",
    paddingVertical: 10,
    marginHorizontal: 15,
    backgroundColor: "white",
  },
});
